package upicgame.comment.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import upicgame.comment.service.CommentService;
import upicgame.entity.Comments;

import javax.annotation.Resource;

import java.util.List;

/*
 *Created by GHW
 *Description:评论Controller
 *2019/12/26 21:20
 */
@Controller
public class CommentController {
    @Resource
    private CommentService cs;

    //添加游戏
    @RequestMapping("addComments")
    public String addComments(Model model, Integer uid, Integer gid, String comments) {
        //用户id 游戏id 评论内容
        try {
            if (uid == null) {
                model.addAttribute("message", "您未登录，请先登陆");
                return null;
            } else if (comments.equals("")) {
                model.addAttribute("message", "评论内容为空");
                return null;
            } else {
                Comments c1 = cs.addComments(uid, gid, comments);
                model.addAttribute("userComments", c1);
                return "game_detail?id="+gid;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "添加评论出错，请检查后重试";
        }
    }

    //显示所有评论
    //使用JSON
    @RequestMapping(value = "showAllComments", produces = "application/json; charset=UTF-8")
    @ResponseBody
    public List<Comments> showAllComments(Model model, Integer gid) {

        try {
            assert gid != null;
            //返回参数列表，包括，评论信息，用户名称，用户头像
            List<Comments> c1 = cs.showAllComments(gid);
            model.addAttribute("showComments", c1);
            return c1;
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failedToLoad", "没有gid");
            return null;
        }
    }

    //删除评论，前端传评论的id回来
    @RequestMapping("delComments")
    public String delComments(Model model, Integer cid) {
        System.out.println(cid);
        try {
            if (cid == null) {
                model.addAttribute("failed", "没有cid");
                return null;
            } else {
                Comments delc = cs.findCommentsById(cid);
                cs.delComments(delc);
                model.addAttribute("success", "删除成功");
                return "comments.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "删除评论出错";
        }
    }

    //管理员显示所有评论
    @RequestMapping("showCommentsToAdmin")
	@ResponseBody
    public List<Comments> showAllCommentsToAdmin(Model model) {
        try {
            List<Comments> comments = cs.showAllCommentsForAdmin();
            model.addAttribute("allComments", comments);
            return comments;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
